﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using DevExpress.XtraTreeList;
using Lamex.mDashboard.Common;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
using Lamex.Library;

namespace Lamex.mDashboard.UI
{
    public partial class frmDashboardViewer : frmBaseChild
    {
        bool blDashboardNavStyle = false;

        static string strRootPath;
        string strFullPath;
        int intGroupHeight;

        List<string> lstPath = new List<string>();
        NavBarControl navBarTree;
        TreeList tvTreeList;

        public frmDashboardViewer()
        {
            InitializeComponent();
        }

        private void frmDashboardViewer_Load(object sender, EventArgs e)
        {
            if (xtraTabControl1.SelectedTabPage.Text == "公共报表")
            {
                strRootPath = @"\\Tx-fs10\tx-fs1\LAMEX\MES\Dashboard";
                navBarTree = navBarTreeRole;
                tvTreeList = tvTreeListRole;
            }
            else
            {
                strRootPath = @"D:\Dashboard";
                navBarTree = navBarTreeUser;
                tvTreeList = tvTreeListUser;
            }

            if (blDashboardNavStyle)
            {
                navBarTree.Dock = DockStyle.Fill;
                navBarTree.Visible = true;
                tvTreeList.Dock = DockStyle.None;
                tvTreeList.Visible = false;
                InitNavBarControl();
            }
            else
            {
                navBarTree.Dock = DockStyle.None;
                navBarTree.Visible = false;
                tvTreeList.Dock = DockStyle.Fill;
                tvTreeList.Visible = true;
                InitTreeListControl();
            }
        }

        private void InitTreeListControl()
        {
            tvTreeList.ClearNodes();
            addDataToTreeList(tvTreeList, strRootPath, 0);
        }

        private void InitNavBarControl()
        {
            navBarTree.Groups.Clear();
            NavBarGroupControlContainer container = null;
            TreeList tv = null;

            //新建list数据源
            List<string> lstGroup = new List<string>();
            lstGroup = GetFolder(strRootPath, lstGroup);
            for (int i = 0; i < lstGroup.Count; i++)
            {
                container = new NavBarGroupControlContainer();
                navBarTree.Controls.Add(container);

                //添加Group
                NavBarGroup group = new NavBarGroup();
                group.Name = lstGroup[i].ToString();
                group.Caption = lstGroup[i].ToString();
                group.ControlContainer = container;
                //group.Expanded = true;
                //group.GroupClientHeight = 410;
                group.GroupClientHeight = 150;
                group.GroupStyle = NavBarGroupStyle.ControlContainer;
                navBarTree.Groups.Add(group);
            }

            //添加Item
            for (int i = 0; i < navBarTree.Groups.Count; i++)
            {
                tv = new TreeList() { Name = "TreeList" + i, Caption = lstGroup[i] };
                tv.Dock = DockStyle.Fill;
                navBarTree.Controls[i].Controls.Add(tv); //必须在这个位置添加控件

                addDataToTreeList(tv, strRootPath + @"\" + lstGroup[i], i);

                navBarTree.Groups[i].GroupClientHeight = intGroupHeight;

                //注册事件
                tv.AfterFocusNode += tv_AfterFocusNode;
            }
        }

        private void addDataToTreeList(TreeList tv, string strDataPath, int i)
        {
            tv.RowHeight = 25;
            tv.OptionsBehavior.Editable = false;
            tv.OptionsSelection.MultiSelect = false;
            tv.OptionsDragAndDrop.DragNodesMode = DragNodesMode.Single; //拖拽开关

            #region ****** 获取并加载数据源 ******

            string keyFieldName = "Id";
            string parentFieldName = "ParentId";
            //新建list数据源
            List<Common.TreeNode> data = new List<Common.TreeNode>();
            data = null;
            //data.Add(new TreeNode() { Id = "root", ParentId = String.Empty, NodeText = "测试1" });
            // data.Add(new TreeNode() { Id = "first", ParentId = "root", NodeText = "测试2" });
            //将指定目录下的所有文件以及文件夹封装成节点对象并添加到list
            data = TreeListHelper.ParseDir(strDataPath, data);
            //添加根节点 Id属性对应根目录的名字， 父级Id为空  节点显示的文本 为 “所有文本”  节点类型为 文件夹
            //data.Add(new TreeNode() { Id = "Dashboard", ParentId = String.Empty, NodeText = "所有文件", NodeType = TreeNodeTypes.Folder });
            //添加单列
            DevExpress.XtraTreeList.Columns.TreeListColumn colNode = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            //设置名字
            colNode.Name = "名字";
            //设置标题
            colNode.Caption = "标题";
            //设置从数据源分配给当前列的字段名。
            colNode.FieldName = "NodeText";
            //设置树列表中显示当前列的位置。
            colNode.VisibleIndex = 0;
            //是否可见
            colNode.Visible = true;
            //是否允许编辑
            colNode.OptionsColumn.AllowEdit = false;
            //是否允许移动   
            colNode.OptionsColumn.AllowMove = false;
            //是否允许移动至自定义窗体    
            colNode.OptionsColumn.AllowMoveToCustomizationForm = false;
            //是否允许排序
            colNode.OptionsColumn.AllowSort = false;
            //是否固定列宽        
            colNode.OptionsColumn.FixedWidth = false;
            //是否只读        
            colNode.OptionsColumn.ReadOnly = true;
            //移除列后是否允许在自定义窗体中显示
            colNode.OptionsColumn.ShowInCustomizationForm = true;
            //先清除列
            tv.Columns.Clear();
            //将列数组添加到集合的结尾。
            tv.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] { colNode });
            tv.OptionsView.ShowColumns = false;             //隐藏列标头
            tv.OptionsView.ShowIndicator = false;           //隐藏节点指示器面板

            tv.OptionsView.ShowHorzLines = false;           //隐藏水平表格线
            tv.OptionsView.ShowVertLines = false;           //隐藏垂直表格线
            tv.OptionsView.ShowIndentAsRowStyle = false;

            //tv.OptionsView.FocusRectStyle = DevExpress.XtraTreeList.DrawFocusRectStyle.None; //在获得焦点的Cell上，是否显示焦点框架。默认为True；
            //颜色设置
            tv.Appearance.Row.BackColor = Color.Transparent;//节点默认背景色
            tv.Appearance.FocusedRow.BackColor = Color.Orange; // 选中节点的背景色
            tv.Appearance.HideSelectionRow.BackColor = Color.LightYellow;//选中节点失去焦点时的背景色

            //设置属性KeyFieldName  ParentFieldName
            //设置一个值，该值指定绑定到XtratreeList控件的数据源的键字段
            tv.KeyFieldName = keyFieldName;
            //设置一个值，该值表示标识此数据源中父记录的数据源字段。
            tv.ParentFieldName = parentFieldName;
            tv.DataSource = data;
            //刷新数据
            tv.RefreshDataSource();

            //setTreeListPortries(tv);//需要更多设置时，可启用

            #endregion

            //取消默认焦点
            tv.FocusedNode = null;
            tv.SetFocusedNode(null);

            if (data.Count <= 8)//最多显示8行
            {
                intGroupHeight = data.Count * 25;
            }
            else
            {
                intGroupHeight = 8 * 25;
            }
        }

        void tv_AfterFocusNode(object sender, NodeEventArgs e)
        {
            getDashboardViewerFile(e, true);
        }

        private void tvTreeList_AfterFocusNode(object sender, NodeEventArgs e)
        {
            getDashboardViewerFile(e, false);
        }

        //获取要查看的Dashboard文件，无法通过TreeList.Node的ID或Tag获取，所以改用遍历实现
        private void getDashboardViewerFile(NodeEventArgs e, bool blIsNavStyle)
        {
            string curNodeText = e.Node.GetValue("NodeText").ToString();
            if (curNodeText.Contains(".xml"))
            {
                if (blIsNavStyle)
                {
                    strFullPath = strRootPath + @"\" + navBarTree.ActiveGroup.Caption.ToString();
                }
                else
                {
                    strFullPath = strRootPath;
                }

                lstPath.Clear();
                lstPath.Add(curNodeText);

                getParentNodes(e.Node);

                //反向遍历List
                for (int i = lstPath.Count - 1; i >= 0; i--)
                {
                    strFullPath += @"\" + lstPath[i];
                }

                try
                {
                    dashboardViewer1.DashboardSource = strFullPath;
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("当前图表文件无法打开！"); //不再提示，因当单击组标题时会触发此提示
                }
            }
        }

        //获取所有父节点
        private void getParentNodes(TreeListNode node)
        {
            if (node.ParentNode != null)
            {
                lstPath.Add(node.ParentNode.GetValue("NodeText").ToString());
                getParentNodes(node.ParentNode);
            }
        }

        //NavBarGroup触发展开或者折叠事件
        private void navBarTree_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DevExpress.XtraNavBar.NavBarControl navBar = sender as DevExpress.XtraNavBar.NavBarControl;
                DevExpress.XtraNavBar.NavBarHitInfo hitInfo = navBar.CalcHitInfo(new Point(e.X, e.Y));
                if (hitInfo.InGroupCaption && !hitInfo.InGroupButton)
                    hitInfo.Group.Expanded = !hitInfo.Group.Expanded;
            }
        }

        //获取指定路径下文件夹，仅下一层
        public static List<string> GetFolder(string path, List<string> FolderList)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            DirectoryInfo[] dii = dir.GetDirectories();
            FileInfo[] fil = dir.GetFiles();
            //加载文件夹
            foreach (DirectoryInfo fd in dii)
            {
                FolderList.Add(fd.Name);//添加文件路径到列表中
            }

            return FolderList;
        }

        private void outLookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            blDashboardNavStyle = true;
            frmDashboardViewer_Load(null, null);
        }

        private void 资源管理器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            blDashboardNavStyle = false;
            frmDashboardViewer_Load(null, null);
        }

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            frmDashboardViewer_Load(null, null);
        }
    }
}